import ClipboardJS from "clipboard";

/**
 *
 * @param {*} text
 * @returns
 */
export const copyText = (text: string) => {
  return new Promise((resolve, reject) => {
    var copyButton = document.createElement("button");
    copyButton.textContent = "复制文本";
    copyButton.style.display = "none";
    copyButton.setAttribute("data-clipboard-text", text);
    const className = `data-clipboard-${Date.now()}`;
    copyButton.className = className;

    document.body.appendChild(copyButton);

    var clipboard = new ClipboardJS(`.${className}`);

    setTimeout(() => {
      copyButton.click();
    }, 0);

    clipboard.on("success", function (e) {
      console.log("复制成功:", e.text);
      e.clearSelection();
      resolve(e.text);

      document.body.removeChild(copyButton);
    });

    clipboard.on("error", function (e) {
      reject("复制失败");
      document.body.removeChild(copyButton);
    });
  });
};
